import { Injectable } from "@nestjs/common";
import { log } from "console";
import Redis from "ioredis";

@Injectable()
export class RedisCacheService {
  constructor(private readonly redis: Redis) { }

  /**
   * 获取redis键值对
   * @param key 键
   * @returns 值
   */
  async get(key: string) {
    try {
      const res = await this.redis.get(key);
      return res
    } catch (error) {
      log(error)
    }
  }

  /**
   * 设置redis
   * @param key 键
   * @param value 值
   * @param ttl 过期时间
   * @returns true or false
   */
  async set(key: string, value: any, ttl: number = 10000) {
    try {
      return await this.redis.set(key, JSON.stringify(value), 'EX', ttl)
    } catch (error) {
      log(error)
    }
  }

  /**
   * 删除redis数据
   * @param keys 键
   * @returns true or false
   */
  async delete(keys: string[]) {
    try {
      return await this.redis.del(keys)
    } catch (error) {
      log(error)
    }
  }
}